package com.explorx.sns.puma.im.core.chat.impl;

import com.explorex.infra.puma.gateway.api.LongLinkPushService;
import com.explorex.infra.puma.gateway.api.dto.LongLinkPushReq;
import com.explorex.puma.common.rpc.RpcResult;
import com.explorx.sns.puma.im.api.ImSendService;
import com.explorx.sns.puma.im.core.chat.PushService;
import com.explorx.sns.puma.im.core.userlink.UserLinkService;
import com.explorx.sns.puma.im.core.userlink.dto.GetUserLinkReq;
import com.explorx.sns.puma.im.core.userlink.dto.UserLinkInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.annotation.DubboReference;
//import org.apache.dubbo.rpc.cluster.specifyaddress.Address;
//import org.apache.dubbo.rpc.cluster.specifyaddress.UserSpecifiedAddressUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PushServiceImpl implements PushService {

    private final int testPort=8848;

    @DubboReference(version = "1.0.0",retries = 2,timeout = 3000,url = "dubbo://localhost:20881")
    private LongLinkPushService longLinkPushService;

    @Resource
    private UserLinkService userLinkService;

    @Override
    public void pushMessage(List<Long> userIds, String pushMsg) {

        // 1. 查询用户在线的情况，是不是在线
        GetUserLinkReq userLinkReq=new GetUserLinkReq();
        userLinkReq.setUids(userIds);
        final List<UserLinkInfo> userLinkInfos = userLinkService.queryUserLink(userLinkReq);

        //1.1 在线发送站内push
        if(!CollectionUtils.isEmpty(userLinkInfos)){
            final Map<String, List<UserLinkInfo>> ip2Links = userLinkInfos.stream().collect(Collectors.groupingBy(UserLinkInfo::getIp));
            for (Map.Entry<String, List<UserLinkInfo>> entry : ip2Links.entrySet()) {
//                UserSpecifiedAddressUtil.setAddress(new Address(entry.getKey(), testPort, true));
                LongLinkPushReq longLinkPushReq=new LongLinkPushReq();
                longLinkPushReq.setContentType(1);
                final List<Long> receiverIds = entry.getValue().stream().map(UserLinkInfo::getUserId).collect(Collectors.toList());
                longLinkPushReq.setReceiverIds(receiverIds);
                longLinkPushReq.setMessage(pushMsg.getBytes(StandardCharsets.UTF_8));
                final RpcResult rpcResult = longLinkPushService.pushMessage(longLinkPushReq);
                System.out.println(rpcResult);
            }
        }
        // 1.2 离线发送站外push

        // 1.3 发送微信小程序通知消息

    }

    private void  sendOnlinePush(){

    }


    private void sendOfflinePush(){

    }

    private void sendWxPush(){

    }
}
